package org.wutopia.leo.infrastructure.jaxrs;


import jakarta.validation.ConstraintViolationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class CustomExceptionHandler {

    private static final Logger log = LoggerFactory.getLogger(CustomExceptionHandler.class);

    /**
     * 用于兜底的全局处理器，如果其他所有的handler都不合适，将由此处理把错误带到前端
     * @param e 异常
     * @return Response
     */

    @ExceptionHandler(Exception.class)
    public ResponseEntity<CodedMessage> handleException(Exception e) {
        // 记录日志、构造响应体
        log.error(e.getMessage(), e);
        return CommonResponse.failure(e.getMessage());
    }

    /**
     * 用于统一处理在Resource中由于验证器验证失败而带回客户端的错误信息
     * @param e 异常
     * @return Response
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public ResponseEntity<CodedMessage> handleViolationException(ConstraintViolationException e) {
        log.warn("客户端传入了校验结果为非法的数据", e);
        String msg = e.getMessage();
        return CommonResponse.send(HttpStatus.BAD_REQUEST, msg);
    }

//    /**
//     * 用于统一处理在Resource中由于Spring Security授权访问产生的异常信息
//     * @param e 异常
//     * @return Response
//     **/
//    @ExceptionHandler(AccessDeniedException.class)
//    public Response handleAccessDeniedException(AccessDeniedException e) {
//        log.warn("越权访问被禁止");
//        return CommonResponse.send(Response.Status.FORBIDDEN, e.getMessage());
//    }
}
